package com.example.program.data.repository

import android.content.Context
import com.example.program.data.local.LocalDataSource
import com.example.program.data.local.RecipesEntity
import com.example.program.data.local.RoomResult
import com.example.program.data.remote.NetworkResult
import com.example.program.data.remote.RemoteDataSource
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import okhttp3.Response
import retrofit2.http.QueryMap

class Repository(val context: Context) {
    private val networkApi = RemoteDataSource.api
    private val roomDao = LocalDataSource.getDao(context)

    companion object{
        val repository = Repository()
    }
    /*
      会回调请求的状态
        正在发起请求
        请求成功
        请求失败
     */
//    suspend fun getRecipes(@QueryMap params: Map<String, String>): Flow<NetworkResult>{
//        //创建flow对象
//        val mFlow = MutableStateFlow<NetworkResult>(NetworkResult.Loading)
//
//        val recipeResponse = networkApi.getRecipes(params)
//        if (recipeResponse.isSuccessful){
//            //告诉外部成功请求的数据
//            mFlow.value = NetworkResult.Success(recipeResponse.body())
//        }else{
//            //告诉外部的原因
//            mFlow.value = NetworkResult.Failure(recipeResponse.message())
//        }
//
//        return mFlow
//    }

    class Repository {
        private val networkApi = RemoteDataSource.api

        /*
          会回调请求的状态
            正在发起请求
            请求成功
            请求失败
         */
//        suspend fun getRecipes(@QueryMap params: Map<String, String>): Flow<NetworkResult>{
//            //创建flow对象
////            val mFlow = MutableStateFlow<NetworkResult>(NetworkResult.Loading)
////
////            val recipeResponse = networkApi.getRecipes(params)
////            if (recipeResponse.isSuccessful){
////                //告诉外部成功请求的数据
////                mFlow.value = NetworkResult.Success(recipeResponse.body())
////            }else{
////                //告诉外部的原因
////                mFlow.value = NetworkResult.Failure(recipeResponse.message())
////            }
////
////            return mFlow
//        }
    }

    suspend fun getRecipes(): Flow<RoomResult> {
        val flow = MutableStateFlow<RoomResult>(RoomResult.Loading)
        val data = roomDao.getRecipes()
        flow.value = RoomResult.Success(data)
        return flow
    }

    suspend fun insertRecipes(entity: RecipesEntity){
        roomDao.insertRecipe(entity)
    }
}